package cn.easyutil.project.web.util;


import cn.easyutil.util.javaUtil.JsonUtil;
import cn.easyutil.project.web.configuration.EasyProjectWebConfiguration;
import cn.easyutil.project.web.session.RedisSessionCache;
import cn.easyutil.project.web.session.ServletSessionCache;
import cn.easyutil.project.web.session.SessionCacheFactory;
import cn.easyutil.project.base.exception.CommonException;
import cn.easyutil.project.base.service.CacheService;
import cn.easyutil.util.javaUtil.LoggerUtil;
import cn.easyutil.util.javaUtil.StringUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import cn.easyutil.project.base.exception.Error;

/**
 * 请求临时对象缓存池
 */
@Component
public class RequestPool implements ApplicationContextAware {

    public static String ENABLE_LOGINURL = "";
    /** 是否开启对参数进行加解密*/
	public static boolean ENABLE_AUTH = false;

    /** 加解密标识（请求的最后一级路径前缀）*/
	public static String ENABLE_AS_LAST_URI_PREFIX = "s-";

    /** 项目约定好的统一请求前缀*/
	public static String URI_PREFIX = "/apis";

    /** 请求头中的token对应的key名称*/
	public static String TOKEN_NAME= "token";

	public static Integer SUCCESSCODE = 200;

	public static Integer ERRORCODE = 500;

	private ApplicationContext applicationContext;

	private static SessionCacheFactory sessionCacheFactory;

	/** 是否使用项目统一包装返回，默认如果是项目约定的前缀则统一包装*/
    public static ThreadLocal<Boolean> useResponse = new ThreadLocal<>();

    @Autowired
    private EasyProjectWebConfiguration configuration;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取缓存
     */
    public static HttpServletRequest get() {
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }

    /**
     * 缓存短信验证码
     * @param phone
     * @param code
     */
    public static void setSmsCode(String phone,String code){
        sessionCacheFactory.setSmsCode(phone,code);
    }

    public static void removeSmsCode(String phone){
        setSmsCode(phone,"");
    }

    /**
     * 获取短信验证码
     * @param phone
     * @return
     */
    public static String getSmsCode(String phone){
        return sessionCacheFactory.getSmsCode(phone);
    }

    /**
     * 为用户签发token
     */
    public static void setToken(String token){
        if(StringUtil.isEmpty(token)){
            throw new CommonException(Error.system_error);
        }
        sessionCacheFactory.setToken(token, null);
    }

    public static void setUserId(Long userId){
        sessionCacheFactory.setToken(getToken(), userId);
    }

    public static void refranshToken(){
        sessionCacheFactory.reletExpire(getToken(),2*60*60);
    }


    /**
     * 获取用户授权的token值，用于解密请求数据
     * @return
     */
    public static String getToken(){
        return get().getHeader(TOKEN_NAME);
    }

    public static void removeToken(){
        sessionCacheFactory.removeToken(getToken());
    }

    /**
     * 获取用户id
     *
     * @return 返回用户id
     */
    public static Long getUserId() {
        String userId = sessionCacheFactory.getUserId(getToken());
        if(null == userId){
            throw new CommonException(Error.user_not_login);
        }
        return Long.parseLong(userId);
    }

    /**
     * 获取用户id(非异常)
     * @return
     */
    public static Long getUserIdNotException(){
        String userId = sessionCacheFactory.getUserId(getToken());
        if(null == userId){
            return null;
        }
        return Long.parseLong(userId);
    }

    /**
     * 设置用户的aes加密串
     * @param aesVal
     */
    public static void setAESKey(String aesVal){
        sessionCacheFactory.setAesKey(getToken(),aesVal);
    }

    /**
     * 获取用户的aes加密串
     * @return
     */
    public static String getAESKey(){
        return sessionCacheFactory.getAesKey(getToken());
    }

    /**
     * 缓存到session信息
     *
     * @param flag 缓存key
     * @param val  缓存数据
     */
    public static void setCacheAttribute(String flag, Object val) {
        sessionCacheFactory.setUserInfo(getToken(),flag, JsonUtil.beanToJson(val));
    }

    /**
     * 获取缓存到session信息
     *
     * @param flag 缓存key
     */
    public static String getCacheAttribute(String flag) {
        return sessionCacheFactory.getUserInfo(getToken(),flag);
    }

    /**
     * 删除缓存到session信息
     *
     * @param flag 缓存key
     */
    public static void removeCacheAttribute(String flag) {
        sessionCacheFactory.setUserInfo(getToken(),flag,"");
    }

    @PostConstruct
    private void init(){
        if(configuration != null){
            ENABLE_AUTH = configuration.isEnableAuth();
            if(configuration.getLoginUrl() != null){
                ENABLE_LOGINURL = configuration.getLoginUrl();
            }
            if(configuration.getUriPrefix() != null){
                URI_PREFIX = configuration.getUriPrefix();
            }
            if(configuration.getTokenName() != null){
                TOKEN_NAME = configuration.getTokenName();
            }
            if(configuration.getEnableAsLastUriPrefix() != null){
                ENABLE_AS_LAST_URI_PREFIX = configuration.getEnableAsLastUriPrefix();
            }
            if(configuration.getSuccessCode() != null){
                SUCCESSCODE = configuration.getSuccessCode();
            }
            if(configuration.getErrorCode() != null){
                ERRORCODE = configuration.getErrorCode();
            }
            if(configuration.isEnableRedis()){
                try {
                    CacheService cache = this.applicationContext.getBean(CacheService.class);
                    sessionCacheFactory = new RedisSessionCache(cache);
                    return;
                } catch (BeansException e) {
                    LoggerUtil.error(RequestPool.class,e.getMessage());
                }
            }
        }
        sessionCacheFactory = new ServletSessionCache();
//        ENABLE_AUTH = enableAuth;
//        ENABLE_AS_LAST_URI_PREFIX = enableAsLastUriPrefix;
//        TOKEN_NAME = tokenName;
//        URI_PREFIX = uriPrefix;
//        ENABLE_LOGINURL = loginUrl;
//    	try {
//            //有缓存实现, 走缓存, 没有走Servlet的session
//            CacheService cache = this.applicationContext.getBean(CacheService.class);
//            sessionCacheFactory = new RedisSessionCache(cache);
//        }catch (Exception e){
//            sessionCacheFactory = new ServletSessionCache();
//            LoggerUtil.warn(RequestPool.class,e.getMessage());
//        }
    }
}
